package com.googlecode.grt192.HH11.sensor;

import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.JComponent;

import com.googlecode.grtframework.event.SwitchEvent;
import com.googlecode.grtframework.event.SwitchListener;
import com.googlecode.grtframework.sensor.ISwitch;
import com.googlecode.grtframework.vis.IMountedPosition;
import com.googlecode.grtframework.vis.Mountable;
import com.googlecode.grtframework.vis.Select;

/**
 * Simulation of a button switch
 * 
 * @author ajc
 * 
 */
public class SimSwitch implements ISwitch, MouseListener, Mountable {

	private Vector listeners;

	private boolean state;

	private final JComponent comp;
	private final IMountedPosition pos;

	public SimSwitch(JComponent comp, IMountedPosition pos) {
		this.comp = comp;
		this.pos = pos;
		listeners = new Vector();
	}

	@Override
	public double getHeading() {
		return pos.getHeading();
	}

	@Override
	public int getX() {
		return pos.getX();
	}

	@Override
	public int getY() {
		return pos.getY();
	}

	@Override
	public void addSwitchListener(SwitchListener arg0) {
		listeners.add(arg0);
	}

	@Override
	public void removeSwitchListener(SwitchListener arg0) {
		listeners.remove(arg0);
	}

	@Override
	public void start() {
		comp.addMouseListener(this);
	}

	@Override
	public void mouseClicked(MouseEvent arg0) {

	}

	@Override
	public void mouseEntered(MouseEvent arg0) {

	}

	@Override
	public void mouseExited(MouseEvent e) {

	}

	@Override
	public void mousePressed(MouseEvent e) {

	}

	public void notifyListeners() {
		SwitchEvent ev = new SwitchEvent(this, state ? SwitchEvent.PRESSED
				: SwitchEvent.RELEASED);
		if (state == STATE_PRESSED) {
			for (Enumeration<SwitchListener> e = listeners.elements(); e
					.hasMoreElements();) {
				e.nextElement().switchPressed(ev);
			}
		} else if (state == STATE_RELEASED) {
			for (Enumeration<SwitchListener> e = listeners.elements(); e
					.hasMoreElements();) {
				e.nextElement().switchReleased(ev);
			}
		}
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// System.out.println(e);
		// toggle by the right click rule
		if (Select.LeftClick.shouldToggleSelect(e, new Point(getX(), getY()))) {
			state = !state; // toggle state
			notifyListeners();
		}

	}

}
